<template>
  <div class="container">
    <div class="app-container">
      <el-tree default-expand-all :data="tree" :props="defaultProps" :expand-on-click-node="false">
        <template #default="{ data }">
          <el-row style="width: 100%; height:40px" align="middle" type="flex" justify="space-between">
            <span>{{ data.name }}</span>
            <el-col :span="4">
              <span class="manager-el">{{ data.managerName }}</span>
              <el-dropdown @command="handleCommand(data.id,$event)">
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                  <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                  <el-dropdown-item command="del">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-col>
          </el-row>
        </template>
      </el-tree>
    </div>
    <addDept ref="addDept" :type-name="typeName" :current-id="currentId" :show-dialog.sync="showDialog" @updataData="getData" />
  </div>
</template>

<script>
import { delDepartment, getdepartment } from '@/api/department'
import { translateDataToTree } from '@/utils'
import addDept from './components/add-dept.vue'

export default {
  name: 'Department',
  components: {
    addDept
  },
  data() {
    return {
      tree: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      showDialog: false,
      currentId: null,
      typeName: ''
    }
  },
  created() {
    this.getData()
  },
  methods: {
    async getData() {
      const res = await getdepartment()
      this.tree = translateDataToTree(res, 0)
    },
    async handleCommand(data, command) {
      if (command === 'add') {
        this.showDialog = true
        this.currentId = data
        this.typeName = '新增部门'
      }
      if (command === 'edit') {
        this.showDialog = true
        this.currentId = data
        this.typeName = '编辑部门'
        // this.$message.success('编辑部门成功')
        this.$nextTick(() => {
          this.$refs.addDept.editDepartmentInfo()
        })
      }
      if (command === 'del') {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        })
        await delDepartment(data)
        this.$message.success('删除部门成功')
        this.getData()
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.app-container {
  width: 100%;
  padding: 20px 50px;
}

.manager-el {
  width: 120px;
  display: inline-block;
}

.el-dropdown-link {
  cursor: pointer;
  color: #409EFF;
}

.el-icon-arrow-down {
  font-size: 12px;
}
</style>
